﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.DynamicData;

namespace NotAClue.Web.DynamicData
{
    public static class UploadExtensionMethods
    {
        /// <summary>
        /// If the given table contains a column that has a UI Hint with the value "DbImage", finds the ScriptManager
        /// for the current page and disables partial rendering
        /// </summary>
        /// <param name="page"></param>
        /// <param name="table"></param>
        public static void DisablePartialRenderingForUpload(this Page page, MetaTable table)
        {
            foreach (var column in table.Columns)
            {
                // TODO this depends on the name of the field template, need to fix
                if (String.Equals(
                    column.UIHint, "DBImage", StringComparison.OrdinalIgnoreCase) ||
                    String.Equals(column.UIHint, "FileImage", StringComparison.OrdinalIgnoreCase) ||
                    String.Equals(column.UIHint, "FileUpload", StringComparison.OrdinalIgnoreCase))
                {
                    var sm = ScriptManager.GetCurrent(page);
                    if (sm != null)
                        sm.EnablePartialRendering = false;

                    break;
                }
            }
        }

        public static String GetUploadPath(String fileUploadPath, String tableName, String pk, String columnName)
        {
            //return empty string if upload path is empty
            if (String.IsNullOrEmpty(fileUploadPath))
                return String.Empty;

            // upload path = path + /{tableName}/{ColumnName}/{PrimaryKeyValue}/
            var uploadPath = fileUploadPath;
            var lastChar = uploadPath.Substring(uploadPath.Length - 1, 1);
            var path = (lastChar == "/" ? uploadPath : uploadPath + "/") + "{0}/{1}/{2}/";

            return String.Format(path, tableName, columnName, pk);
        }
    }
}